/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.Util;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * @author Bashan
 */
public class VideoInfo {
  private String ffmpegApp;
  private int hours;
  private int minutes;
  private float seconds;
  public VideoInfo(String ffmpegApp) {
    this.ffmpegApp = ffmpegApp;
  }
  public void getInfo(String videoFilename)
      throws IOException, InterruptedException {
    String tmpFile = videoFilename + ".tmp.png";
    ProcessBuilder processBuilder = new ProcessBuilder(ffmpegApp, "-y", "-i", videoFilename, "-vframes", "1",
        "-ss", "0:0:0", "-an", "-vcodec", "png", "-f", "rawvideo", "-s", "100*100", tmpFile);
    Process process = processBuilder.start();
    InputStream stderr = process.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    String line;
    StringBuffer sb = new StringBuffer();
    while ((line = br.readLine()) != null) {
      sb.append(line);
    }
    new File(tmpFile).delete();
    Pattern pattern = Pattern.compile("Duration: (.*?),");
    Matcher matcher = pattern.matcher(sb);
    if (matcher.find()) {
      String time = matcher.group(1);
      calcTime(time);
    }
    process.waitFor();
  }
  private void calcTime(String timeStr) {
    String[] parts = timeStr.split(":");
    hours = Integer.parseInt(parts[0]);
    minutes = Integer.parseInt(parts[1]);
    seconds = Float.parseFloat(parts[2]);
  }
  public int getHours() {
    return hours;
  }
  public int getMinutes() {
    return minutes;
  }
  public float getSeconds() {
    return seconds;
  }
  public static void main(String[] args) {
    VideoInfo videoInfo = new VideoInfo("C:\\ffmpeg.exe");
    try {
      videoInfo.getInfo("C:\\Mortal-Kombat-PS-Vita-Trailer.mp4");
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}